#
#  This library provides a function to comfortable use GNU units (http://www.gnu.org/software/units/)
#  in a shell script. It is made to use with libinclude.sh.
#  
#  Synopsis:
#     units_clc EQUATION
#     units_clc [-n|-u] EQUATION_with_UNITS|VALUE_with_UNITS
#     units_clc [-n|-u] EQUATION_with_UNITS|VALUE_with_UNITS UNITS
#
#     units_clc [-n|-u] EQUATION | VALUE [UNITS]
#
# depends on units

#IF {uname -a | grep FreeBSD && gunits -t 1} > /dev/null 2>/dev/null
    units=gunits
#ELIF uname -a | grep FreeBSD
    echo 'Dependecy gunits not met.'
    exit 1
#ELSE
    units=units
#FI

with_units=1

clc () {
	local wunits out p1 p2 pin
	
	wunits=$with_units
	pin=''
	
	# read in command line parameter
	while [ "$1" ]; do
   	case "$1" in
    	'-u'|'--units') wunits=1;;
      '-n'|'--nounits') wunits=0;;
    	*) pin="$pin;${1}"
   	esac
   	shift
	done

	p1="$(echo $pin | cut -d';' -f2)"
      p2="$(echo $pin | cut -d';' -f3)"

	if [ "$p1" ] && [ "$p2" ]; then
		out=`$units -t "$p1" "$p2"`
	elif [ "$p1" ];then
		out=`$units -t "$p1"`
	else
		echo "(units.sh) ERROR: No input!"
		exit 1
	fi
	
	if [ "$(echo $out | cut -d' ' -f1-2)" = 'conformability error' ]; then
		echo "(units.sh) ERROR: ($1) =/=> ($2) !"
		exit 1
	elif [ "$(echo $out | cut -d' ' -f1-2)" = 'Unknown unit' ]; then
		echo "(units.sh) ERROR: $out !"
		exit 1
	elif [ "$(echo $out | cut -d' ' -f1)" = 'Error' ]; then
		echo "(units.sh) ERROR: $out !"
		exit 1
	fi	
	
	if [ "$(echo $out | cut -d':' -f1)" = 'Definition' ]; then
		if [ $wunits -eq 1 ]; then
			result="$(echo $out | cut -d':' -f2)"
		else
			result="$(echo $out | cut -d' ' -f2)"
		fi
	else
		if [ $wunits -eq 1 ]; then
			result="$out $p2"
		else
			result="$out"
		fi
	fi
	
	echo $result	
}	
